import { createVNode as _createVNode } from "vue";
import { ref, watch, computed, nextTick, onUpdated, onMounted, defineComponent } from "vue";
import { isHidden, truthProp, makeStringProp, makeNumericProp, createNamespace } from "../utils/index.mjs";
import { useRect, useScrollParent, useEventListener } from "@vant/use";
import { useExpose } from "../composables/use-expose.mjs";
import { useTabStatus } from "../composables/use-tab-status.mjs";
import { Loading } from "../loading/index.mjs";
const [name, bem, t] = createNamespace("list");
const listProps = {
  error: Boolean, // 是否加载失败, 加载失败后点击提示错误
  offset: makeNumericProp(300), // 滚动条与底部距离小于 offset 时触发 load 事件
  loading: Boolean, // 滚动条与底部距离小于 offset 时触发
  disabled: Boolean,
  finished: Boolean, // 是否已加载完成，加载完成后不再触发 load 事件
  scroller: Object, // 指定需要监听滚动事件的节点，默认为最近的父级滚动节点  慎用!!!
  errorText: String, // 加载失败后的提示文案
  direction: makeStringProp("down"),
  loadingText: String, // 加载过程中的提示文案
  finishedText: String, // 加载完成后的提示文
  immediateCheck: truthProp // 是否在初始化时立即执行滚动位置检查
};
var stdin_default = defineComponent({
  name,
  props: listProps,
  emits: ["load", "update:error", "update:loading"],
  setup(props, {
    emit,
    slots
  }) {
    // 接收双向绑定值
    const loading = ref(props.loading);
    const root = ref();
    const placeholder = ref();
    // 使用tab组件provide的数据
    const tabStatus = useTabStatus();
    // 找到最近的可以滚动父节点
    const scrollParent = useScrollParent(root);
    // 慎用scroller, 使用默认window作为scroller
    const scroller = computed(() => props.scroller || scrollParent.value);
    // 检测是否需要加载下一页
    const check = () => {
      nextTick(() => {
        // loading.value || props.finished || props.disabled || props.error  状态时不检查
        if (loading.value || props.finished || props.disabled || props.error || // skip check when inside an inactive tab
        (tabStatus == null ? void 0 : tabStatus.value) === false) {
          return;
        }
        const {
          direction
        } = props;
        const offset = +props.offset;
        // 父级可以滚动的容器 rect
        const scrollParentRect = useRect(scroller);
        // 当父级容器高度为空 或 list隐藏时  退出不检查
        if (!scrollParentRect.height || isHidden(root)) {
          return;
        }
        let isReachEdge = false;
        const placeholderRect = useRect(placeholder);
        if (direction === "up") {
          isReachEdge = scrollParentRect.top - placeholderRect.top <= offset;
        } else {
          // down时 placeholder在content下面
          // 当placeholderRect滚动到还差offset距离可见时, 开始加载数据
          // 父节点都没有加scroll时, placeholderRect返回值中width和height 分别为innerWidth和innerHeight
          isReachEdge = placeholderRect.bottom - scrollParentRect.bottom <= offset;
        }
        // isReachEdge为true时 触发loadding事件
        if (isReachEdge) {
          loading.value = true;
          emit("update:loading", true);
          emit("load");
        }
      });
    };

    // 完成渲染函数
    const renderFinishedText = () => {
      if (props.finished) {
        const text = slots.finished ? slots.finished() : props.finishedText;
        if (text) {
          return _createVNode("div", {
            "class": bem("finished-text")
          }, [text]);
        }
      }
    };
    // 点击加载错误提示文字
    const clickErrorText = () => {
      emit("update:error", false);
      check();
    };
    // 加载错误提示渲染函数
    const renderErrorText = () => {
      if (props.error) {
        const text = slots.error ? slots.error() : props.errorText;
        if (text) {
          return _createVNode("div", {
            "role": "button",
            "class": bem("error-text"),
            "tabindex": 0,
            "onClick": clickErrorText
          }, [text]);
        }
      }
    };

    // loading状态渲染函数
    const renderLoading = () => {
      // finished 和 disabled的优先级大于loading
      if (loading.value && !props.finished && !props.disabled) {
        return _createVNode("div", {
          "class": bem("loading")
        }, [
          // 有插槽使用插槽  无插槽 在loading默认插槽中  插入loadingText
          slots.loading ? slots.loading() : _createVNode(Loading, {
          "class": bem("loading-icon")
        }, {
          default: () => [props.loadingText || t("loading")]
        })]);
      }
    };

    // props.loading, props.finished, props.error 监听改变时
    watch(() => [props.loading, props.finished, props.error], check);
    // 配合tab使用时, 切换检查是否需要loading
    if (tabStatus) {
      watch(tabStatus, (tabActive) => {
        if (tabActive) {
          check();
        }
      });
    }

    onUpdated(() => {
      loading.value = props.loading;
    });
    // 初始时, 默认检测加载第一页
    onMounted(() => {
      if (props.immediateCheck) {
        check();
      }
    });
    // 暴露外部使用
    useExpose({
      check
    });

    useEventListener("scroll", check, {
      target: scroller,
      passive: true
    });

    return () => {
      var _a;
      // 外部 插槽放入的遍历内容
      const Content = (_a = slots.default) == null ? void 0 : _a.call(slots);
      // 用于检查是否需要加载 计算ele
      const Placeholder = _createVNode("div", {
        "ref": placeholder,
        "class": bem("placeholder")
      }, null);
      return _createVNode("div", {
        "ref": root,
        "role": "feed",
        "class": bem(),
        "aria-busy": loading.value
      }, [
        // direction决定 loadingText finishedText  errorText的位置
        props.direction === "down" ? Content : Placeholder, 
        renderLoading(), 
        renderFinishedText(), 
        renderErrorText(), 
        props.direction === "up" ? Content : Placeholder
      ]);
    };
  }
});
export {
  stdin_default as default,
  listProps
};
